<template>
  <div class="word-management">
    <div class="page-header">
      <h2>单词管理</h2>
      <div class="header-actions">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索单词"
          :prefix-icon="Search"
          style="width: 300px; margin-right: 16px"
          clearable
          @keyup.enter="handleSearch"
        />
        <el-button type="success" :icon="Upload" @click="handleImport">批量导入</el-button>
        <el-button type="primary" :icon="Plus" @click="handleAdd">添加单词</el-button>
        <el-button :icon="Refresh" @click="loadWords">刷新</el-button>
      </div>
    </div>

    <!-- 单词列表表格 -->
    <el-table
      :data="tableData"
      style="width: 100%"
      v-loading="loading"
      :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
    >
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="word" label="单词" width="150" show-overflow-tooltip />
      <el-table-column prop="phonetic" label="音标" width="150" />
      <el-table-column prop="meaning" label="释义" min-width="200" show-overflow-tooltip />
      <el-table-column prop="exampleSentenceEn" label="例句" min-width="250" show-overflow-tooltip />
      <el-table-column prop="createdAt" label="录入时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="260" fixed="right">
        <template #default="{ row }">
          <div class="action-buttons">
            <el-button type="primary" size="small" :icon="View" @click="handleView(row)">
              查看
            </el-button>
            <el-button type="warning" size="small" :icon="Edit" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)">
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑单词对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="单词" prop="word">
          <el-input v-model="formData.word" placeholder="请输入单词" />
        </el-form-item>
        <el-form-item label="音标" prop="phonetic">
          <el-input v-model="formData.phonetic" placeholder="如: /wɜːd/" />
        </el-form-item>
        <el-form-item label="释义" prop="meaning">
          <el-input
            v-model="formData.meaning"
            type="textarea"
            :rows="3"
            placeholder="请输入单词释义"
          />
        </el-form-item>
        <el-form-item label="英文例句" prop="exampleSentenceEn">
          <el-input
            v-model="formData.exampleSentenceEn"
            type="textarea"
            :rows="2"
            placeholder="请输入英文例句"
          />
        </el-form-item>
        <el-form-item label="中文例句" prop="exampleSentenceCn">
          <el-input
            v-model="formData.exampleSentenceCn"
            type="textarea"
            :rows="2"
            placeholder="请输入中文翻译"
          />
        </el-form-item>
        <el-form-item label="音频URL" prop="audioUrl">
          <el-input v-model="formData.audioUrl" placeholder="请输入音频文件URL（可选）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="单词详情" width="600px">
      <el-descriptions :column="1" border v-if="currentWord">
        <el-descriptions-item label="单词ID">{{ currentWord.id }}</el-descriptions-item>
        <el-descriptions-item label="单词">
          <span style="font-size: 18px; font-weight: bold">{{ currentWord.word }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="音标">{{ currentWord.phonetic || '-' }}</el-descriptions-item>
        <el-descriptions-item label="释义">{{ currentWord.meaning || '-' }}</el-descriptions-item>
        <el-descriptions-item label="英文例句">
          {{ currentWord.exampleSentenceEn || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="中文例句">
          {{ currentWord.exampleSentenceCn || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="音频URL">
          {{ currentWord.audioUrl || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="录入时间">
          {{ formatDate(currentWord.createdAt) }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 批量导入对话框 -->
    <el-dialog v-model="importDialogVisible" title="批量导入单词" width="500px">
      <el-alert
        title="导入说明"
        type="info"
        :closable="false"
        style="margin-bottom: 20px"
      >
        <p>请上传Excel文件，格式要求：</p>
        <ul style="margin: 5px 0; padding-left: 20px">
          <li>第一列：单词</li>
          <li>第二列：音标</li>
          <li>第三列：释义</li>
          <li>第四列：英文例句</li>
          <li>第五列：中文例句</li>
        </ul>
      </el-alert>
      <el-upload
        drag
        action="#"
        :auto-upload="false"
        :on-change="handleFileChange"
        :limit="1"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
      </el-upload>
      <template #footer>
        <el-button @click="importDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleImportSubmit" :loading="importing">
          开始导入
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import {
  Search,
  Plus,
  Refresh,
  View,
  Edit,
  Delete,
  Upload,
  UploadFilled
} from '@element-plus/icons-vue'
import { getWordList, getWordById, createWord, updateWord, deleteWord, importWords } from '../api/word'

// 表格数据
const tableData = ref([])
const loading = ref(false)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const importDialogVisible = ref(false)
const dialogTitle = ref('添加单词')
const isEdit = ref(false)
const submitting = ref(false)
const importing = ref(false)
const formRef = ref()
const currentWord = ref(null)
const uploadFile = ref(null)

// 表单数据
const formData = ref({
  id: null,
  word: '',
  phonetic: '',
  meaning: '',
  exampleSentenceEn: '',
  exampleSentenceCn: '',
  audioUrl: ''
})

// 表单验证规则
const formRules = {
  word: [
    { required: true, message: '请输入单词', trigger: 'blur' }
  ],
  meaning: [
    { required: true, message: '请输入释义', trigger: 'blur' }
  ]
}

onMounted(() => {
  loadWords()
})

// 加载单词列表
const loadWords = async () => {
  loading.value = true
  try {
    const response = await getWordList({
      page: currentPage.value,
      size: pageSize.value,
      search: searchKeyword.value
    })
    
    if (response.code === 200) {
      tableData.value = response.data.list
      total.value = response.data.total
    } else {
      ElMessage.error(response.message || '加载单词列表失败')
    }
  } catch (error) {
    console.error('加载单词列表失败：', error)
    ElMessage.error('加载单词列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadWords()
}

// 添加单词
const handleAdd = () => {
  dialogTitle.value = '添加单词'
  isEdit.value = false
  formData.value = {
    id: null,
    word: '',
    phonetic: '',
    meaning: '',
    exampleSentenceEn: '',
    exampleSentenceCn: '',
    audioUrl: ''
  }
  dialogVisible.value = true
}

// 编辑单词
const handleEdit = (row) => {
  dialogTitle.value = '编辑单词'
  isEdit.value = true
  formData.value = { ...row }
  dialogVisible.value = true
}

// 查看详情
const handleView = (row) => {
  currentWord.value = row
  detailDialogVisible.value = true
}

// 删除单词
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除单词"${row.word}"吗？此操作不可恢复。`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await deleteWord(row.id)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        loadWords()
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    } catch (error) {
      console.error('删除单词失败：', error)
      ElMessage.error('删除失败')
    }
  })
}

// 批量导入
const handleImport = () => {
  importDialogVisible.value = true
  uploadFile.value = null
}

// 文件选择
const handleFileChange = (file) => {
  uploadFile.value = file
}

// 导入提交
const handleImportSubmit = async () => {
  if (!uploadFile.value) {
    ElMessage.warning('请选择要导入的文件')
    return
  }
  
  importing.value = true
  try {
    const response = await importWords(uploadFile.value.raw)
    if (response.code === 200) {
      const data = response.data || {}
      const successCount = data.successCount || 0
      const skipCount = data.skipCount || 0
      const errorCount = data.errorCount || 0
      const errors = data.errors || []
      const skippedWords = data.skippedWords || []
      
      // 构建详细提示信息
      let message = response.message || '导入完成'
      let detailMessage = ''
      let type = 'success'
      
      // 根据导入结果确定通知类型和内容
      if (errorCount > 0) {
        type = 'warning'
        detailMessage = `<div style="line-height: 1.8;">
          <p><strong>导入结果：</strong></p>
          <p>✅ 成功导入：<span style="color: #67c23a; font-weight: bold;">${successCount}</span> 个单词</p>
          <p>⚠️ 跳过重复：<span style="color: #e6a23c; font-weight: bold;">${skipCount}</span> 个单词</p>
          <p>❌ 导入失败：<span style="color: #f56c6c; font-weight: bold;">${errorCount}</span> 个单词</p>
        </div>`
        
        // 如果有错误详情，添加到消息中
        if (errors.length > 0) {
          detailMessage += `<div style="margin-top: 10px;"><strong>错误详情：</strong></div><ul style="margin: 5px 0; padding-left: 20px; max-height: 150px; overflow-y: auto;">`
          errors.forEach(error => {
            detailMessage += `<li style="color: #f56c6c;">${error}</li>`
          })
          detailMessage += `</ul>`
        }
      } else if (skipCount > 0 && successCount === 0) {
        type = 'info'
        detailMessage = `<div style="line-height: 1.8;">
          <p><strong>导入结果：</strong></p>
          <p>⚠️ 跳过重复：<span style="color: #e6a23c; font-weight: bold;">${skipCount}</span> 个单词</p>
          <p>✅ 成功导入：<span style="color: #67c23a; font-weight: bold;">${successCount}</span> 个单词</p>
        </div>`
        
        // 如果跳过的单词数量较少，显示列表
        if (skippedWords.length > 0 && skippedWords.length <= 10) {
          detailMessage += `<div style="margin-top: 10px;"><strong>跳过的单词：</strong></div><div style="color: #909399; margin-top: 5px;">${skippedWords.join(', ')}</div>`
        } else if (skippedWords.length > 10) {
          detailMessage += `<div style="margin-top: 10px;"><strong>跳过的单词（前10个）：</strong></div><div style="color: #909399; margin-top: 5px;">${skippedWords.slice(0, 10).join(', ')} 等 ${skipCount} 个</div>`
        }
      } else if (successCount > 0) {
        type = 'success'
        detailMessage = `<div style="line-height: 1.8;">
          <p><strong>导入结果：</strong></p>
          <p>✅ 成功导入：<span style="color: #67c23a; font-weight: bold;">${successCount}</span> 个单词</p>
          ${skipCount > 0 ? `<p>⚠️ 跳过重复：<span style="color: #e6a23c; font-weight: bold;">${skipCount}</span> 个单词</p>` : ''}
        </div>`
        
        // 如果有跳过的单词且数量不多，也显示列表
        if (skipCount > 0 && skippedWords.length > 0 && skippedWords.length <= 5) {
          detailMessage += `<div style="margin-top: 10px;"><strong>跳过的单词：</strong></div><div style="color: #909399; margin-top: 5px;">${skippedWords.join(', ')}</div>`
        }
      } else {
        type = 'info'
        detailMessage = message
      }
      
      // 显示详细通知
      ElNotification({
        title: '批量导入完成',
        message: detailMessage,
        type: type,
        duration: errorCount > 0 ? 0 : 5000, // 有错误时不自动关闭，让用户有时间查看错误信息
        dangerouslyUseHTMLString: true,
        position: 'top-right'
      })
      
      // 刷新列表以显示最新数据
      loadWords()
      
      // 关闭对话框
      importDialogVisible.value = false
    } else {
      ElMessage.error(response.message || '导入失败')
    }
  } catch (error) {
    console.error('导入失败：', error)
    ElMessage.error('导入失败：' + (error.message || '网络错误'))
  } finally {
    importing.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        let response
        if (isEdit.value) {
          // 更新单词
          response = await updateWord(formData.value.id, formData.value)
        } else {
          // 创建单词
          response = await createWord(formData.value)
        }
        
        if (response.code === 200) {
          ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
          dialogVisible.value = false
          loadWords()
        } else {
          ElMessage.error(response.message || '操作失败')
        }
      } catch (error) {
        console.error('操作失败：', error)
        ElMessage.error('操作失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 分页
const handleSizeChange = (size) => {
  pageSize.value = size
  loadWords()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadWords()
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<style scoped>
.word-management {
  padding: 24px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  font-size: 20px;
  color: #303133;
  margin: 0;
}

.header-actions {
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-alert p) {
  margin: 5px 0;
}

:deep(.el-alert ul) {
  margin: 5px 0;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: nowrap;
}

.action-buttons .el-button {
  margin: 0 !important;
}
</style>

